#if UNITY_EDITOR
using GameDesigner;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEditor.IMGUI.Controls;
using UnityEditor.SceneManagement;
using UnityEngine.SceneManagement;

namespace UnityToolbarExtender.Examples
{
    [InitializeOnLoad]
    public sealed class SceneSwitchLeftButton
    {
        private static List<(string sceneName, string scenePath)> m_Scenes;
        private static Dictionary<string, string> Scenes = new();
        private static string sceneName;
        private static Texture2D icon;

        static SceneSwitchLeftButton()
        {
            EditorApplication.projectChanged += UpdateCurrent;
            UpdateCurrent();
            ToolbarExtender.RightToolbarGUI.Add(OnToolbarGUI);
        }

        static void UpdateCurrent()
        {
            m_Scenes = SceneHelper.GetAllScenesInProject();
            Scenes = new Dictionary<string, string>();
            for (int i = 0; i < m_Scenes.Count; i++)
            {
                var (name, path) = m_Scenes[i];
                Scenes[name] = path;
            }
            icon = EditorGUIUtility.IconContent("d_SceneAsset Icon").image as Texture2D;
            sceneName = SceneManager.GetActiveScene().name;
        }

        static void OnToolbarGUI()
        {
            if (Scenes.Count <= 0) //空项目0场景判断
                return;
            var guiContent = new GUIContent(sceneName);
            var size = EditorStyles.popup.CalcSize(guiContent);
            EditorGUILayout.LabelField("游戏场景", GUILayout.Width(50));
            GUILayout.Label(icon, GUILayout.Width(20), GUILayout.Height(20));
            var scRect = EditorGUILayout.GetControlRect(GUILayout.Width(size.x + 5f), GUILayout.MinWidth(55));
            if (EditorGUI.DropdownButton(scRect, guiContent, FocusType.Passive))
            {
                var dropdown = new AddPopupWindow("Select Scenes", Scenes.Keys.ToList(), new AdvancedDropdownState(), "d_SceneAsset Icon");
                var maximumSize = dropdown.GetType().GetProperty("maximumSize", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
                maximumSize?.SetValue(dropdown, new Vector2(scRect.width, 800f));
                dropdown.Init(scRect, (currSelect) =>
                {
                    var value = Scenes[currSelect];
                    SceneHelper.PromptSaveCurrentScene();
                    EditorSceneManager.OpenScene(value);
                    sceneName = currSelect;
                });
            }
        }
    }

    static class SceneHelper
    {
        public static bool PromptSaveCurrentScene()
        {
            // 检查当前场景是否已保存
            if (SceneManager.GetActiveScene().isDirty)
            {
                // 提示用户是否要保存当前场景
                bool saveScene = EditorUtility.DisplayDialog(
                    "Save Current Scene",
                    "The current scene has unsaved changes. Do you want to save it?",
                    "Save",
                    "Cancel"
                );

                // 如果用户选择“保存”，则保存当前场景
                if (saveScene)
                {
                    EditorSceneManager.SaveScene(SceneManager.GetActiveScene());
                }

                return saveScene;
            }

            // 如果场景已保存或者用户选择了“取消”，则返回 true，表示继续执行后续操作
            return true;
        }

        /// <summary>
        /// 获取项目中所有的场景文件，并以 (场景名, 场景路径) 的形式返回。
        /// </summary>
        public static List<(string sceneName, string scenePath)> GetAllScenesInProject()
        {
            var scenes = new List<(string sceneName, string scenePath)>();

            // 查找所有场景文件
            string[] guids = AssetDatabase.FindAssets("t:Scene");
            for (int i = 0; i < guids.Length; i++)
            {
                var guid = guids[i];
                string path = AssetDatabase.GUIDToAssetPath(guid);
                string sceneName = $"{i + 1}_{Path.GetFileNameWithoutExtension(path)}";
                scenes.Add((sceneName, path));
            }
            return scenes;
        }
    }
}
#endif